import Axios from 'axios'

const state = {
	treeData: [],			//树形结构
	tableData: [],
	expandNodeId: [],		//展开高亮节点
    row: [],
    rowId: null,            //更新资料的id
    parentId: [],           //分管部门id
    parentName: [],         //分管部门名称
    multipleSelection: [],
    selectRowId: []
}

const mutations = {
	updateExpandNodeId(state, id) {
		state.expandNodeId.splice(0, 1, id);
	},
    updateRowId(state, id) {
        state.rowId = id ? id : null;
    },
    updateRow(state, row) {
        state.row.splice(0, 1, row);
    },
    updateParentId(state, id) {             //更新分管部门id
        state.parentId.splice(0, 1, id);
    },
    updateParentName(state, name) {             //更新分管部门名称
        state.parentName.splice(0, 1, name);
    },
	updateTableData(state, arr) {
		let treeData = state.treeData,
            tableData = state.tableData,
            expandNodeId = state.expandNodeId[0];
        if(arr) {
            if(arr.length > 0) {
                tableData.length = 0;
                arr.forEach(item => {
                    item['level'] = 1;
                    tableData.push(item);
                });
            } else {
                tableData.splice(0);
            }
        } else {
            treeData.forEach(item => {
                if(item['id'] == expandNodeId) {
                    if(item['suppliers'] && item['suppliers'].length > 0) {
                        tableData.length = 0;
                        item['suppliers'].forEach(item => {
                            item['level'] = 1;
                            tableData.push(item);
                        });
                    } else {
                        tableData.splice(0);
                    }
                }
            });
        }
	},
	multipleSelection(state, arr) {
        state.multipleSelection.length = 0;
        state.selectRowId.length = 0;
        if(arr.length > 0) {
            arr.forEach(item => {
                state.multipleSelection.push(item);
                state.selectRowId.push(item['id']);
            });
        } else {
            state.multipleSelection.splice(0);
            state.selectRowId.splice(0);
        }
    }
}

const actions = {
	getTreeData({state, commit}) {		//获取树形结构数据
		Axios.get('supplier/selectTree').then(res => {
			if(res.data.code == 20001) {
				if(res.data.data) {
					let treeData = state.treeData,
                        data = res.data.data;
                    treeData.length = 0;
                    if(state.expandNodeId.length == 0) {
                        state.expandNodeId.splice(0, 1, data[0]['id']);
                        state.row.splice(0, 1, data[0]);
                    }
                    data.forEach(item => {
                        item['level'] = 0;
                        treeData.push(item);
                    });
                    commit('updateTableData');          //更新表格数据
				}
			}
		});
	}
}


export default {
	namespaced: true,
	state,
	mutations,
	actions
}